package com.miyu.system.service.weather.impl;

import com.alibaba.fastjson.JSONObject;
import com.miyu.common.pojo.WebServicePJ;
import com.miyu.common.utils.comService.WebHttpService;
import com.miyu.common.utils.ehcache.EhcacheUtil;
import com.miyu.system.service.weather.WeatherService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class WeatherServiceImpl implements WeatherService {


    /**
     * reids 指定缓存名称 空间
     * 可达到不同的数据缓存到不同的空间中
     * cacheNames #30 指定过期时间 默认秒
     * @param param
     * @return
     * @throws Exception
     */
    @Cacheable(cacheNames = {"weather#3600"},key = "#param.getString('vCity')")
    @Override
    public JSONObject queryWeather(JSONObject param) throws Exception {
        String key = param.getString("vCity");
        String version ="";
        version=param.getString("version");
        String city = param.getString("city");
        JSONObject rs = new JSONObject();
        //数据进行缓存 校验数据是否有 如果有是否超过两小时 如果超过一个小时更新 否者直接取值返回不再更新时间
        StringBuffer url = new StringBuffer();
        url.append("https://www.tianqiapi.com/api?");
        url.append("unescape=1");
        url.append("&version=").append(version);
        url.append("&appid=16319171&appsecret=Ywlwceu5");
        url.append("&cityid=").append(city);
        if(EhcacheUtil.getInstance().hasKey("weather",key)){
            rs = (JSONObject) EhcacheUtil.getInstance().get("weather",key );
        }else {
            // 返回结果字符串
            String result = null;
            WebServicePJ pj = new WebServicePJ();
            pj.setUrl(url.toString());
            pj.setMethod("GET");
            result = WebHttpService.getWebHttpServiceStr(pj);
            if(result.length()>0) {
                rs = JSONObject.parseObject(result);
            }
            EhcacheUtil.getInstance().put("weather",key ,rs,3600);
        }
        return rs;
    }
}
